﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Drawing;
using System.IO;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Web.Caching;
using System.Net;
using System.Runtime.Remoting.Contexts;
using Icst.Leaflike.Logging;

namespace Icst.Leaflike.Web
{
    public class TreeThumbnail : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            string id = context.Request["id"];
            string name = context.Request["name"];
            int width = !string.IsNullOrEmpty(context.Request["w"]) ? int.Parse(context.Request["w"]) : 64;
            int height = !string.IsNullOrEmpty(context.Request["h"]) ? int.Parse(context.Request["h"]) : 64;
            string cachekey = name + width + height;
            Bitmap bmpTree = null;
            try
            {
                bmpTree = context.Cache[cachekey] as Bitmap;
            }
            catch { }

            if (bmpTree == null)
            {
                try
                {
                    string fileName = context.Server.MapPath("~/trees/" + name);
                    bmpTree = new Bitmap(fileName);
                    bmpTree = bmpTree.GetProportionalResizedImage(width, height, true, false).CompressImage(96);
                    context.Cache[cachekey] = bmpTree;
                }
                catch(Exception e) 
                {
                    Logger.Error("FAILED TO GET TREE THUMBNAIL with " + name + ". " + e.Message);
                }
            }

            try
            {
                if (bmpTree != null)
                {
                    bmpTree.SaveToJpgStream(context.Response.OutputStream);
                }
            }
            catch (Exception e)
            {
                Logger.Error("FAILED TO SAVE THUMBNAIL with " + name + ". " + e.Message);
            }
        }
        public bool IsReusable { get { return false; } }
    }
}
